<template>
  <div class="app-container">
    <div style="display: flex; margin-bottom: 20px">

      <div style="margin-left: 20px">
        <el-button type="primary" size="big" @click="showAdd()">添加</el-button>
      </div>
    </div>
    <!-- <el-form>
      <el-form-item>
        <el-button type="primary" @click="showAdd()">添加新闻</el-button>
      </el-form-item>
    </el-form> -->
    <!-- 添加新闻 -->
    <el-dialog title="添加" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="120px">
        <el-upload
          class="upload-demo"
          action=""
          :on-change="onChange1"
          :on-remove="onRemove1"
          :file-list="fileList1"
          list-type="picture"
          :http-request="subUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAdd('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改" :visible.sync="dialogForm">
      <el-form :ref="Editform" :model="Editform" label-width="120px">
        <el-upload
          ref="uploadAvatar"
          class="upload-demo"
          action=""
          :on-change="onChange"
          :on-remove="onRemove"
          :file-list="[{ name: 'newPng', url: Editform.image }]"
          :limit="1"
          :http-request="subUpload1"
          list-type="picture-card"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
          >选取文件</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">取 消</el-button>
        <el-button type="primary" @click="doEdit('Editform')">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="图片" width="110" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.image" width="50px" height="50px">
        </template>
      </el-table-column>
      <el-table-column label="排序" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column
        class-name="status-col"
        label="状态"
        width="90"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status1 == 1"
            :type="scope.row.status1 | statusFilter"
          >正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="创建时间"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="updated_at"
        label="更新时间"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="260">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="showEdit(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteNews(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      align="center"
      background
      :current-page="params.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="params.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getCate } from '@/api/banner'
import { addCate } from '@/api/banner'
import { editCate } from '@/api/banner'
import { delCate } from '@/api/banner'
import TinyMce from '@/components/Tinymce'
export default {
  components: {
    TinyMce
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogForm: false,
      dialogVisible: false,
      fileList: [],
      fileList1: [],
      newCate: [],
      form: {
        image: ''
      },
      total: 1,
      Editform: {
        id: '',
        image: ''
      },
      params: {
        title: '',
        page: 1,
        limit: 5
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 修改图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传图片验证
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, '')
      if (
        [
          'jpg',
          'png',
          'txt',
          'zip',
          'rar',
          'pdf',
          'doc',
          'docx',
          'xlsx'
        ].indexOf(FileExt.toLowerCase()) === -1
      ) {
        this.$message({
          type: 'warning',
          message:
            '请上传后缀名为jpg、png、txt、pdf、doc、docx、xlsx、zip或rar的附件！'
        })
        return false
      }
    },
    // 上传图片
    subUpload() {
      const formData = new FormData()
      formData.append('image', this.fileList1[0].raw)
      addCate(formData).then((res) => {
        this.success(res)
      })
    },
    subUpload1() {
      const formData = new FormData()
      formData.append('path', this.fileList[0].raw)
      addCate(formData).then((res) => {
        this.success1(res)
      })
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    onRemove(file) {
      this.fileList.map((item) => {
        if (item.uid === file.uid) {
          item.status = 'removed'
        }
      })
    },
    // 显示添加
    showAdd() {
      this.dialogFormVisible = true
    },
    // 添加
    doAdd(formName) {
      this.dialogFormVisible = false
      this.fetchData()
    },
    onChange1(file, fileList1) {
      this.fileList1 = fileList1
    },
    onRemove1(file) {
      this.fileList1.map((item) => {
        if (item.uid === file.uid) {
          item.status = 'removed'
        }
      })
    },
    // 显示修改
    showEdit(info) {
      this.dialogForm = true
      this.Editform.image = info.image
      this.Editform.id = info.id
    },
    // 确认修改
    doEdit(formName) {
      editCate(this.Editform).then((res) => {
        if (res.code == 20000) {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.dialogForm = false
          this.fetchData()
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 删除
    deleteNews(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delCate(id).then((res) => {
            if (res.code == 20000) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.fetchData()
            } else {
              this.$message({
                message: '删除失败',
                type: 'error'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分页
    handleSizeChange(val) {
      this.params.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.params.page = val
      this.fetchData()
    },
    // 搜索
    searchList() {
      this.fetchData()
    },

    success(res) {
      if (res.code == 20000) {
        this.form.image = res.data.savePath
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg)
        // 请求失败后清空文件列表
        this.$refs.uploadAvatar.clearFiles()
      }
    },
    success1(res) {
      if (res.code == 20000) {
        this.Editform.image = res.data.savePath
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg)
        // 请求失败后清空文件列表
        this.$refs.uploadAvatar.clearFiles()
      }
    },

    fetchData() {
      this.listLoading = true
      getCate(this.params).then((response) => {
        this.list = response.data.data
        this.listLoading = false
        this.total = response.data.total
      })
      getCate().then((res) => {
        this.newCate = res.data.data
      })
    }
  }
}
</script>
